
import sys
import os
import json

try: import sqlite3
except ImportError:
    try: from pysqlite2 import dbapi2 as sqlite3
    except ImportError:
        print 'Please, install sqlite3 module'
        sys.exit()  

DATA_DIR = os.path.realpath(os.path.dirname(__file__) + '/../data')
EXAMPLE_DIR = os.path.realpath(os.path.dirname(__file__) + '/../examples')
DEFAULT_SETUP = {'webport': 7777}

db_schema = '''
DROP TABLE IF EXISTS "results";
CREATE TABLE "results" ("id" INTEGER PRIMARY KEY NOT NULL, "uid" INTEGER NOT NULL, "shared" INTEGER DEFAULT 0, "checksum" TEXT, "structure" TEXT, "energy" REAL, "phonons" TEXT, "electrons" TEXT, "info" TEXT, "apps" TEXT);

DROP TABLE IF EXISTS "topics";
CREATE TABLE "topics" ("tid" INTEGER PRIMARY KEY NOT NULL, "categ" INTEGER NOT NULL, "topic" TEXT);

DROP TABLE IF EXISTS "tags";
CREATE TABLE "tags" ("checksum" TEXT, "tid" INTEGER NOT NULL, FOREIGN KEY(tid) REFERENCES topics(tid));
'''

# INSTALL MODE
if not os.path.exists( os.path.abspath(  DATA_DIR + '/settings.~'  ) ):
    settings = DEFAULT_SETUP
    if not os.path.exists(DATA_DIR): os.makedirs(DATA_DIR)
    f = open(DATA_DIR + '/settings.~', 'w')
    f.writelines(json.dumps(settings))
    f.close()
    
# CREATE DB IF NOT FOUND
if not os.path.exists( os.path.abspath(  DATA_DIR + '/tilde.dat'  ) ):
    conn = sqlite3.connect( os.path.abspath(  DATA_DIR + '/tilde.dat'  ) )
    cursor = conn.cursor()
    for i in db_schema.splitlines():
        cursor.execute( i )
    conn.commit()
    conn.close()
    os.chmod(os.path.abspath(  DATA_DIR + '/tilde.dat'  ), 0777)    
    
try: settings
except NameError:
    try: settings = json.loads( open( DATA_DIR + '/settings.~' ).read() )
    except ValueError: raise RuntimeError('Your settings JSON seems not to be well-formatted, please, pay attention to commas and quotes!')

# SETTINGS DEFINITION
if not 'local_dir' in settings: settings['local_dir'] = None
if not 'demo_regime' in settings: settings['demo_regime'] = 0
if not 'debug_regime' in settings: settings['debug_regime'] = 0
if not 'quick_regime' in settings: settings['quick_regime'] = 0
if not 'filter' in settings: settings['filter'] = 0
if not 'title' in settings: settings['title'] = 0

# SETTINGS COMBINATIONS
if settings['demo_regime'] and settings['debug_regime']: settings['debug_regime'] = 0
    